//
//  BuscadorViewController.m
//  FinApp
//
//  Created by Marcel Arbó Lack on 11/11/11.
//  Copyright (c) 2011 FIB-Fàcultat d'informàtica de Barcelona. All rights reserved.
//

#import "BuscadorViewController.h"
#import "ResultadosBusquedaViewController.h"
#import "AppDelegate.h"
#import "ListFlat.h"
#import "TrackingViewController.h"

@interface BuscadorViewController()
- (void) buildSegmented;
- (void)moveButtonsViewToYPosition:(int)position;
@end

@implementation BuscadorViewController

@synthesize segmentedControl, navigationBar, pickerView, okButton, picker, buttonsView;
@synthesize inmobleButton, provinciaButton, poblacioButton;
@synthesize segonaMaLabel, segonaMaImage, segonaMaButton, aEstrenarLabel, aEstrenarImage, aEstrenarButton, nomesVacacionalLabel, nomesVacacionalImage, nomesVacacionalButton;
@synthesize buscarButton;
@synthesize inmobleArray, provinciaArray, poblacioArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"_buscador", @"");
        self.tabBarItem.image = [UIImage imageNamed:@"tabbar_icon_buscador"];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
    [self setSegmentedControl:nil]; [self setNavigationBar:nil];
    [self setInmobleButton:nil]; [self setProvinciaButton:nil]; [self setPoblacioButton:nil];
    [self setInmobleArray:nil]; [self setProvinciaArray:nil]; [self setPoblacioArray:nil];
    [self setSegonaMaLabel:nil]; [self setSegonaMaImage:nil]; [self setSegonaMaButton:nil];
    [self setAEstrenarLabel:nil]; [self setAEstrenarImage:nil]; [self setAEstrenarButton:nil];
    [self setNomesVacacionalLabel:nil]; [self setNomesVacacionalImage:nil]; [self setNomesVacacionalButton:nil];
    [self setBuscarButton:nil];
    [self setPicker:nil]; [self setOkButton:nil]; [self setButtonsView:nil]; [self setPickerView:nil];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self buildSegmented];
    
    //Set buscarButton title
    [buscarButton setTitle:NSLocalizedString(@"_buscar", @"") forState:UIControlStateNormal];
    
    //Hide navigationController
    [self.navigationController setNavigationBarHidden:YES];
    
    //Set button placeholders titles
    [inmobleButton setTitle:NSLocalizedString(@"_tipusHabitatge", @"") forState:UIControlStateNormal];
    [provinciaButton setTitle:NSLocalizedString(@"_provincia", @"") forState:UIControlStateNormal];
    [poblacioButton setTitle:NSLocalizedString(@"_poblacio", @"") forState:UIControlStateNormal];
    
    //Set titles
    [segonaMaLabel setText:NSLocalizedString(@"_segonaMa", @"")];
    [aEstrenarLabel setText:NSLocalizedString(@"_aEstrenar", @"")];
    [nomesVacacionalLabel setText:NSLocalizedString(@"_nomesVacacional", @"")];
    
    //Init datasource Arrays
    inmobleArray = [[NSArray alloc] initWithObjects:NSLocalizedString(@"_habitatge", @""),
                    NSLocalizedString(@"_local", @""),
                    NSLocalizedString(@"_oficina", @""),
                    NSLocalizedString(@"_plaçaGaratge", @""),
                    NSLocalizedString(@"_traster", @""),
                    NSLocalizedString(@"_naus", @""),
                    NSLocalizedString(@"_terreny", @""),
                    NSLocalizedString(@"_diversos", @""),
                    NSLocalizedString(@"_hotel", @""),
                    NSLocalizedString(@"_edifici", @""),nil];

    provinciaArray = [[NSArray alloc] initWithObjects:NSLocalizedString(@"_qualsevol", @""),
                      @"Barcelona",
                      @"Madrid",
                      @"Sevilla",
                      @"Valencia", nil];
    
    poblacioArray = [[NSArray alloc] initWithObjects:NSLocalizedString(@"_qualsevol", @""),
                     @"Alella",
                     @"Barcelona",
                     @"Canet",
                     @"Girona",
                     @"Tordera",nil];
    
    UIBarButtonItem *tracking = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico_settings.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(openTracking)];
    [navigationBar.topItem setRightBarButtonItem:tracking];
    [tracking release];
}

- (void)openTracking {
    TrackingViewController *trackingVC = [[TrackingViewController alloc] initWithNibName:@"TrackingViewController" bundle:nil];
    [trackingVC setHidesBottomBarWhenPushed:YES];
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.5];
    [self.navigationController pushViewController:trackingVC animated:NO]; 
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO]; 
    [UIView commitAnimations];
    [trackingVC release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [self setSegmentedControl:nil]; [self setNavigationBar:nil];
    [self setInmobleButton:nil]; [self setProvinciaButton:nil]; [self setPoblacioButton:nil];
    [self setInmobleArray:nil]; [self setProvinciaArray:nil]; [self setPoblacioArray:nil];
    [self setSegonaMaLabel:nil]; [self setSegonaMaImage:nil]; [self setSegonaMaButton:nil];
    [self setAEstrenarLabel:nil]; [self setAEstrenarImage:nil]; [self setAEstrenarButton:nil];
    [self setNomesVacacionalLabel:nil]; [self setNomesVacacionalImage:nil]; [self setNomesVacacionalButton:nil];
    [self setBuscarButton:nil];
    [self setPicker:nil]; [self setOkButton:nil]; [self setButtonsView:nil]; [self setPickerView:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Private Methods

- (void) buildSegmented {
    //Add mySegmentedControl to navigationBar
    NSArray *segmentedItemsArray = [[NSArray alloc] initWithObjects:NSLocalizedString(@"_compra",@""), NSLocalizedString(@"_lloguer",@""), nil];
    segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentedItemsArray];
    [segmentedItemsArray release];
    segmentedControl.frame = CGRectMake(0, 0, 146, 30);
    segmentedControl.tintColor = [UIColor blackColor];
    segmentedControl.center = navigationBar.center;
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBezeled;
    segmentedControl.selectedSegmentIndex = 0;
    [self.view addSubview:segmentedControl];
}

#define kInmoblesPosition   64
#define kProvinciaPosition  20
#define kPoblacioPosition   -22

- (void)showPicker:(id)sender {
    UIButton *presedButton = (UIButton *)sender;
    //Move buttonsView for each button
    switch (presedButton.tag) {
        case 0: //inmoble
            picker.tag = 0;
            okButton.tag = 0;
            [picker reloadAllComponents];
            [self moveButtonsViewToYPosition:kInmoblesPosition];
            break;
        case 1: //provincia
            picker.tag = 1;
            okButton.tag = 1;
            [picker reloadAllComponents];
            [self moveButtonsViewToYPosition:kProvinciaPosition];
            break;
        case 2: //poblacio
            picker.tag = 2;
            okButton.tag = 2;
            [picker reloadAllComponents];
            [self moveButtonsViewToYPosition:kPoblacioPosition];
            break;
        default:
            break;
    }
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    [pickerView setFrame:CGRectMake(0, 151, 320, 260)];
    [UIView commitAnimations];
}

- (void)hidePicker:(id)sender {
    
    //Move buttonsView to original position
    [self moveButtonsViewToYPosition:64];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    [pickerView setFrame:CGRectMake(0, 411, 320, 260)];
    [UIView commitAnimations];
}

- (void)moveButtonsViewToYPosition:(int)position {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    [buttonsView setFrame:CGRectMake(0, position, 320, 176)];
    [UIView commitAnimations];
}

- (void)segonaMaButtonPressed:(id)sender {
    UIButton *presedButton = (UIButton *)sender;
    if (presedButton.tag == 0) {
        [segonaMaButton setTag:1];
        [segonaMaImage setImage:[UIImage imageNamed:@"buscador_checkOn"]];
        [segonaMaLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14]];
    }
    else {
        [segonaMaButton setTag:0];
        [segonaMaImage setImage:[UIImage imageNamed:@"buscador_checkOff"]];
        [segonaMaLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:13]];
    }
}

- (void)aEstrenarButtonPressed:(id)sender {
    UIButton *presedButton = (UIButton *)sender;
    if (presedButton.tag == 0) {
        [aEstrenarButton setTag:1];
        [aEstrenarImage setImage:[UIImage imageNamed:@"buscador_checkOn"]];
        [aEstrenarLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14]];
    }
    else {
        [aEstrenarButton setTag:0];
        [aEstrenarImage setImage:[UIImage imageNamed:@"buscador_checkOff"]];
        [aEstrenarLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:13]];
    }
}

- (void)nomesVacacionalButtonPressed:(id)sender {
    UIButton *presedButton = (UIButton *)sender;
    if (presedButton.tag == 0) {
        [nomesVacacionalButton setTag:1];
        [nomesVacacionalImage setImage:[UIImage imageNamed:@"buscador_checkOn"]];
        [nomesVacacionalLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14]];
    }
    else {
        [nomesVacacionalButton setTag:0];
        [nomesVacacionalImage setImage:[UIImage imageNamed:@"buscador_checkOff"]];
        [nomesVacacionalLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:13]];
    }
}

- (IBAction)buscarButtonPressed:(id)sender {
    
    float searchType = [segmentedControl selectedSegmentIndex];
    NSString *inmoble = [[inmobleButton titleLabel] text];
    NSString *provincia = [[provinciaButton titleLabel] text];
    NSString *poblacio = [[poblacioButton titleLabel] text];
    BOOL segonaMa = segonaMaButton.tag;
    BOOL aEstrenar = aEstrenarButton.tag;
    BOOL nomesVacacional = nomesVacacionalButton.tag;
    
    [[RestConsumer sharedInstance] searchHousesWithFiltersType:searchType inmoble:inmoble provincia:provincia poblacio:poblacio segonaMa:segonaMa aEstrenar:aEstrenar nomesVacacional:nomesVacacional withDelegate:self];
    
    [(AppDelegate*)[[UIApplication sharedApplication] delegate] removeBigActivity];
    [(AppDelegate*)[[UIApplication sharedApplication] delegate] showBigActivityWithText:NSLocalizedString(@"_buscanInmobles", @"")];
}

#pragma mark - Public Methods

#pragma mark - UIPickerView delegate methods

// returns width of column and height of row for each component.
/*
 - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
 
 }
 */

/*
 - (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
 
 }
 */

// these methods return either a plain UIString, or a view (e.g UILabel) to display the row for the component.
// for the view versions, we cache any hidden and thus unused views and pass them back for reuse. 
// If you return back a different object, the old one will be released. the view will be centered in the row rect
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
	NSString *res = @"";
	switch (picker.tag) {
        case 0: //inmoble
            res = [inmobleArray objectAtIndex:row];
            break;
        case 1: //provincia
            res = [provinciaArray objectAtIndex:row];
            break;
        case 2: //poblacio
            res = [poblacioArray objectAtIndex:row];
            break;
        default:
            break;
    }	
	return res;
}


/*
 - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
 }
 */


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSString *selectedOption;
    switch (okButton.tag) {
        case 0: //inmoble
            selectedOption = [inmobleArray objectAtIndex:row];
            [inmobleButton.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14]];
            [inmobleButton setTitle:selectedOption forState:UIControlStateNormal];
            break;
        case 1: //provincia
            selectedOption = [provinciaArray objectAtIndex:row];
            [provinciaButton.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14]];
            [provinciaButton setTitle:selectedOption forState:UIControlStateNormal];
            break;
        case 2: //poblacio
            selectedOption = [poblacioArray objectAtIndex:row];
            [poblacioButton.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14]];
            [poblacioButton setTitle:selectedOption forState:UIControlStateNormal];
            break;
        default:
            break;
    }
}


#pragma mark - UIPickerView datasource methods

// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
	return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
	NSInteger res = 0;
	switch (picker.tag) {
        case 0: //inmoble
            res = [inmobleArray count];
            break;
        case 1: //provincia
            res = [provinciaArray count];
            break;
        case 2: //poblacio
            res = [poblacioArray count];
            break;
        default:
            break;
    }	
	return res;
}

#pragma mark - DataFetchingHandler

-(void)dataFetchingDidFailWithTag:(NSString*)tag andError:(NSError*)error {
    [(AppDelegate*)[[UIApplication sharedApplication] delegate] removeBigActivity];
}

-(void)dataFetchingCompleteWithTag:(NSString*)tag data:(id)aData andStatus:(NSInteger)status{
    NSDictionary *response = (NSDictionary*)aData;
    if ([[response objectForKey:@"responseCode"] intValue] != 200) {
        [self dataFetchingDidFailWithTag:tag andError:nil];
        return;
    }
    if ([tag isEqualToString:kSEARCHHOUSESTAG]) {
        //Get Data
        [(AppDelegate*)[[UIApplication sharedApplication] delegate] removeBigActivity];
        NSMutableArray *flats = [[NSMutableArray alloc] init];
        for (NSDictionary *flatDict in [response objectForKey:@"inmobles"]) {
            [flats addObject:[ListFlat listFlatFromDictionary:flatDict]];
        }
        
        ResultadosBusquedaViewController *resultadosBusquedaViewController = [[ResultadosBusquedaViewController alloc] initWithNibName:@"ResultadosBusquedaViewController" bundle:nil];
        [resultadosBusquedaViewController setFlats:flats];
        [resultadosBusquedaViewController setHidesBottomBarWhenPushed:YES];
        [[self navigationController] pushViewController:resultadosBusquedaViewController animated:YES];
        [resultadosBusquedaViewController release];
        
    }
}


@end
